//
//  GJFMerchantDetailViewController.m
//  Wedding
//
//  Created by 郭静芬 on 2017/1/2.
//  Copyright © 2017年 郭静芬. All rights reserved.
//

#import "GJFMerchantDetailViewController.h"
#import "GJFMerchantDetailHeaderView.h"
#import "GJFMerchantDetailTagTableViewCell.h"
#import "GJFMerchantDetailIntroduceTableViewCell.h"
#import "GJFMerchantDetailTelTableViewCell.h"
#import "GJFMerchantDetailCaseTableViewCell.h"
#import "GJFMapViewController.h"
#import "GJFInspirationDetailViewController.h"

@interface GJFMerchantDetailViewController ()<UITableViewDelegate, UITableViewDataSource, GJFMerchantDetailTelDelegate, GJFMerchantDetailCaseTableViewCellDelegate, UMSocialShareMenuViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) GJFMerchantDetailHeaderView *headerView;
@property (nonatomic, strong) GJFMerchantModel *merchantModel;
@property (nonatomic, strong) UILabel *introduce;
@property (nonatomic, strong)UILabel *caseName;
@property (nonatomic, strong)UILabel *number;
@end

@implementation GJFMerchantDetailViewController

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    for (UIView *v in self.navigationController.navigationBar.subviews) {
        v.alpha = 1.0;
    }
    [self.navigationController.navigationBar setBackgroundImage:[GJFSingleTool imageWithColor:HOMECOLOR] forBarMetrics:UIBarMetricsDefault];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsCompact];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    self.navigationController.navigationBar.barTintColor = [UIColor clearColor];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon-返回"] style:UIBarButtonItemStyleDone target:self action:@selector(popVc)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon-分享"] style:UIBarButtonItemStyleDone target:self action:@selector(shareAction)];
    
    [self getMerchantDetailData];
    [self tableView];
}
#pragma mark - 点击返回按钮pop到详情页面
- (void)popVc {
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 点击分享
- (void)shareAction {
    [GJFSingleTool shareToViewController:self title:self.merchantModel.nickname content:self.merchantModel.introduction image:self.merchantModel.banner_res url:SHAREURL];
}
#pragma mark - 网络请求商户详情页面的数据
- (void)getMerchantDetailData {
    NSDictionary *dict = @{@"mid":self.mid?:@""};
    [GJFNetworkTool POSTRequestWithUrl:APP_MERCHANT_DETAIl params:dict complete:^(NSDictionary *result) {
        if ([result[@"code"] intValue] == 1000) {
            self.merchantModel = [GJFMerchantModel mj_objectWithKeyValues:result[@"data"]];
            
            [self.headerView.imageV sd_setImageWithURL:[NSURL URLWithString:self.merchantModel.banner]];
            self.headerView.name.text = self.merchantModel.nickname;
            [self.headerView.imageUser sd_setImageWithURL:[NSURL URLWithString:self.merchantModel.avatar]];
            
            self.headerView.frame = CGRectMake(0, -HEADERHEIGHT, WIDTH, HEADERHEIGHT);
            [self.headerView refreshFrameWithOffset:0];
            [self.tableView reloadData];
        }
    }];
}
#pragma mark - TableView每个分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}
#pragma mark - TableView每个分区中row数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        if (self.merchantModel.taglist.length == 0) {
            return 0;
        }
    }
    else if (section == 3) {
        return self.merchantModel.myCase.count;
    }
    return 1;
}
#pragma mark - TableView每个分区中cell的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        GJFMerchantDetailTagTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TagCell"];
        cell.merchantModel = self.merchantModel;
        return cell;
    }
    else if (indexPath.section == 1){
        GJFMerchantDetailIntroduceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"IntroduceCell"];
        cell.merchantModel = self.merchantModel;
        return cell;
    }
    else if (indexPath.section == 2){
        GJFMerchantDetailTelTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TelCell"];
        cell.merchantModel = self.merchantModel;
        //指定代理人
        cell.delegate = self;
        return cell;
    }
    else {
        GJFMerchantDetailCaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CaseCell"];
        cell.caseModel = self.merchantModel.myCase[indexPath.row];
        cell.caseDelegate = self;
        return cell;
    }
}
#pragma mark - TableView分区头部的内容
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        UIView *header_view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 30)];
        [header_view addSubview:self.introduce];
        return header_view;
    }
    else if(section == 3) {
        UIView *header_view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 30)];
        self.number.text = [NSString stringWithFormat:@"%ld个",self.merchantModel.myCase.count];
        [header_view addSubview:self.caseName];
        [header_view addSubview:self.number];
        return header_view;
    }
    return nil;
}
#pragma mark - TableView每个分区中row的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        NSArray *array = [self.merchantModel.taglist componentsSeparatedByString:@","];
        if (array.count > 4) {
            return 120 * YY;
        }
        return 80 * YY;
    }
    else if (indexPath.section == 1){
        CGFloat h = [GJFSingleTool heightWithText:self.merchantModel.introduction fontSize:18 Width:WIDTH - 20 * XX];
        return h + 40 * YY;
    }
    else if (indexPath.section == 2){
        return 80 * YY;
    }
    else {
        return 150 * YY;
    }
}
#pragma mark - TableView每个分区头部的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1 || section == 3) {
        return 40 * YY;
    }
    else {
        return 0.1;
    }
}
#pragma mark - TableView每个分区尾部的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}
#pragma mark - 当scrollView将要拉动时，导航栏将会出现
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.navigationItem.title = self.merchantModel.nickname;
}
#pragma mark - 根据scrollView偏移量的改变，最上面封装的视图发生变化，以及导航栏透明度的改变
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    //获取偏移量
    CGPoint offset = scrollView.contentOffset;
    //判断是否改变
    CGRect rect = self.headerView.frame;
    if (offset.y < 0) {
        //我们只需要改变图片的高度即可
        rect.size.height = - offset.y;
        rect.origin.y = offset.y;
        [self.headerView refreshFrameWithOffset:scrollView.contentOffset.y + HEADERHEIGHT];
    }
    else {
        //我们只需要改变图片的y即可
        rect.origin.y = - offset.y;
    }
    self.headerView.frame = rect;
    
    // 更改导航栏透明度
    CGFloat alpha = (offset.y + HEADERHEIGHT) / 64;
    if (alpha >= 1) {
        alpha = 0.99;
    }
    // 设置导航条的背景图片 其透明度随  alpha 值 而改变
    for (UIView *v in self.navigationController.navigationBar.subviews) {
        NSString *vStr = NSStringFromClass(v.class);
        if ([vStr isEqualToString:@"UINavigationButton"]) {
            [v setAlpha:1.0];
        }
        else {
            [v setAlpha:alpha];
        }
        NSLog(@"%@", v);
    }
    UIImage *image = [GJFSingleTool imageWithColor:[UIColor colorWithRed:0.46 green:0.17 blue:0.28 alpha:alpha]];
    [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
}

#pragma mark - 实现协议方法：点击详情页面位置，跳转到地图的协议方法
- (void)clickLocationActionWithLatitude:(NSString *)latitude longitude:(NSString *)longitude {
    GJFMapViewController *mapVC = [[GJFMapViewController alloc] init];
    [self presentViewController:[[UINavigationController alloc] initWithRootViewController:mapVC] animated:YES completion:^{
        [mapVC goLocationWithLatitude:latitude Longitude:longitude];
    }];
}
#pragma mark - 实现协议方法：点击详情页面电话，弹出拨打电话的协议方法
- (void)clickTelAction {
    NSMutableString *str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@", self.merchantModel.telephone?:@"18840859942"];
    if (![[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]]) {
        [self.view showWarning:@"该设备不支持电话功能"];
    }
}
#pragma mark - 实现协议方法：点击详情页面案例，跳转到灵感页面
- (void)caseSkipDetailWithArray:(NSArray *)array IndexPath:(NSIndexPath *)indexPath {
    GJFInspirationDetailViewController *inspirationDetailVC = [[GJFInspirationDetailViewController alloc] init];
    inspirationDetailVC.inspirationArr = array;
    inspirationDetailVC.indexP = indexPath;
    [self.navigationController pushViewController:inspirationDetailVC animated:YES];
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -64, WIDTH, HEIGHT) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView addSubview:self.headerView];
        _tableView.contentInset = UIEdgeInsetsMake(HEADERHEIGHT, 0, 0, 0);
        [_tableView registerClass:[GJFMerchantDetailTagTableViewCell class] forCellReuseIdentifier:@"TagCell"];
        [_tableView registerClass:[GJFMerchantDetailIntroduceTableViewCell class] forCellReuseIdentifier:@"IntroduceCell"];
        [_tableView registerClass:[GJFMerchantDetailTelTableViewCell class] forCellReuseIdentifier:@"TelCell"];
        [_tableView registerClass:[GJFMerchantDetailCaseTableViewCell class] forCellReuseIdentifier:@"CaseCell"];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
- (GJFMerchantDetailHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[GJFMerchantDetailHeaderView alloc] init];
    }
    return _headerView;
}
- (UILabel *)introduce {
    if (!_introduce) {
        _introduce = [[UILabel alloc] initWithFrame:CGRectMake(125 * XX, 10 * YY, 125 * XX, 30 * YY)];
        _introduce.text = @"商户简介";
        _introduce.textAlignment = NSTextAlignmentCenter;
        _introduce.textColor = HOMECOLOR;
        _introduce.font = [UIFont systemFontOfSize:19 * XX];
    }
    return _introduce;
}
- (UILabel *)caseName {
    if (!_caseName) {
        _caseName = [[UILabel alloc] initWithFrame:CGRectMake(125 * XX, 10 * YY, 125 * XX, 30 * YY)];
        _caseName.text = @"案例";
        _caseName.textAlignment = NSTextAlignmentCenter;
        _caseName.textColor = HOMECOLOR;
        _caseName.font = [UIFont systemFontOfSize:19 * XX];
    }
    return _caseName;
}
- (UILabel *)number {
    if (!_number) {
        _number = [[UILabel alloc] initWithFrame:CGRectMake(250 * XX, 10, 105 * XX, 30 * YY)];
        _number.textAlignment = NSTextAlignmentRight;
        _number.textColor = [UIColor darkGrayColor];
    }
    return _number;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
